<template>
  <div class="all">
    <div class="class">
      <div class="class-header">
        <div class="header-left">
          <div class="line"></div>
          <div class="title">销售统计</div>
          <el-date-picker
            v-model="searchStartTime"
            type="month"
            placeholder="选择开始时间"
            style="width: 150px"
            value-format="YYYY-MM"
            class="className1"
          ></el-date-picker>
          <div class="line2"></div>
          <el-date-picker
            v-model="searchEndTime"
            type="month"
            placeholder="选择结束时间"
            style="width: 150px"
            value-format="YYYY-MM"
            class="className1"
          ></el-date-picker>
          <div style="position: relative">
            <el-button @click="handleSearch" class="search">搜索</el-button>
            <img src="../../assets/images/搜索.png" class="searchImg" alt="" />
          </div>
        </div>
        <div class="header-right"></div>
      </div>
    </div>

    <div class="class-content">
      <el-table
        :data="tableData"
        class="tableMaxHeight"
        v-if="flag"
      >
        <el-table-column prop="userName" label="姓名" align="center" width="155" fixed="left" v-if="user.roleId=='1'|| user.roleId=='2'" />
        <template v-for="month in monthArr" :key="month" >
          <el-table-column width="420" :label="month" align="center">
            <!-- ... 已有代码 ... -->
            <el-table-column label="月录入人数" :width="user.roleId == '5' ? '165' : '140'" align="center">
              <template #default="{ row }">
                {{ row.achievements[month] ? row.achievements[month].signUpNum : '---' }}
              </template>
            </el-table-column>
            <el-table-column label="转成在习生的数量"  :width="user.roleId == '5' ? '180' : '150'" align="center">
              <template #default="{ row }">
                {{
                  row.achievements[month]
                    ? row.achievements[month].transformNum == null
                      ? '---'
                      : row.achievements[month].transformNum
                    : '---'
                }}
              </template>
            </el-table-column>
            <el-table-column label="月转化率" :width="user.roleId == '5' ? '160':'140'" align="center">
              <template #default="{ row }">
                {{
                  row.achievements[month]
                    ? row.achievements[month].changeRate == null
                      ? '---'
                      : row.achievements[month].changeRate
                    : '---'
                }}
              </template>
            </el-table-column>
          </el-table-column>
        </template>
        <el-table-column label="总录入人数（月）" align="center" fixed="right" width="150">
          <template #default="{ row }">
            {{ sum(row) }}
          </template>
        </el-table-column>
        <el-table-column
          label="总转化人数（月）"
          fixed="right"
          align="center"
          width="150"
        >
          <template #default="{ row }">
            {{ sumTransform(row) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="80" align="center" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" @click="handleDetail(row)">详情</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-table
        :data="tableData1"
        class="tableMaxHeight"
        v-if="!flag"
      >
        <el-table-column prop="userName" label="姓名" align="center" v-if="user.roleId==1||user.roleId==2" />
        <el-table-column prop="totalSignUpNum" label="总录入人数" align="center" >
          <template #default="{ row }">
            {{ row.totalSignUpNum ? row.totalSignUpNum : '---' }}
          </template>
        </el-table-column>
        <el-table-column prop="totalTransformNum" label="总转化人数" align="center" >
          <template #default="{ row }">
            {{ row.totalTransformNum? row.totalTransformNum : '---' }}
          </template>
        </el-table-column>
        <el-table-column prop="totalChange" label="总转化率" fixed="right" align="center" >
          <template #default="{ row }">
            {{ row.totalChange? row.totalChange : '---' }}
          </template>
        </el-table-column>
      </el-table>
    </div>

    <el-dialog
      v-model="dialogVisible"
      :show-close="false"
      custom-class="my-dialog-class"
      style="padding: 0"
    >
      <template #header>
        <div class="custom-dialog-header">
          <span>销售详情</span>
        </div>
      </template>
      <el-table :data="detailData" style="width: 100%">
        <el-table-column prop="studentName" label="姓名" align="center" />
        <el-table-column prop="preDate" label="预报到时间" align="center" />
        <el-table-column prop="tel" label="电话" align="center" />
      </el-table>
      <div class="page1">
        <el-pagination
          background
          layout="prev, pager, next"
          :total="total"
          :page-size="pageSize"
          :current-page="currentPage"
          @current-change="handleCurrentChange"
        />
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel" class="cancel">取消</el-button>
          <el-button type="primary" @click="confirm" class="confirm"> 确定 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
  
  <script setup>
import { ref, onMounted, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { salesCount, salesCountDetail,totalCount } from '../api/shop'




// 分页
let total = ref(0) // 总条数
let pageSize = ref(6) // 每页显示条数
let currentPage = ref(1) // 当前页码
let userId = ref()
let detailData = ref([])
let searchStartTime = ref('')
let searchEndTime = ref('')
let tableData = ref([])
let afterchievements = ref([])
//存储月份
let monthArr = []
//表格数据
let tableData1 = ref([])

//销售端详情时间
const time = ref('')

//本地数据
const user = JSON.parse(localStorage.getItem('user'))



//显示
let flag = ref(false)


//获取总数据
function getTotal(){
  let params = reactive({})
  if(user.roleId == '5' ){
    params.userId = user.userId
  }
  totalCount(params).then((res)=>{
    if(res.code == 200){
      tableData1.value = res.dataset
    }
  })
}





// 获取数据
let getData = async () => {
  if (user.roleId == '1' || user.roleId == '2' || user.roleId == '5') {
    let params = reactive({
      beginMonth: searchStartTime.value ,
      endMonth: searchEndTime.value ,
    })
    if (user.roleId == '5') {
      params.userId = user.userId
    }
    afterchievements.value = []
    salesCount(params).then((res) => {
      if (res.code == 200) {
        tableData.value = res.dataset
        for (let index in tableData.value) {
          afterchievements.value.push(tableData.value[index].achievements)
        }
        getMonth(afterchievements.value)
        flag.value = true
      } else {
        ElMessage({
          message: '获取数据失败',
          type: 'error',
        })
      }
    })
  }
}
//求和
function sum(row) {
  let total = 0
  for (let item of monthArr) {
    if (row.achievements[item] != null) {
      total += row.achievements[item].signUpNum
    }
  }
  return total
}

function sumTransform(row) {
  let total = 0
  for (let item of monthArr) {
    if (row.achievements[item]!= null) {
      total += row.achievements[item].transformNum
    }
  }
  return total
}

// 搜索
const handleSearch = () => {
  if(searchStartTime.value && searchEndTime.value && new Date(searchStartTime.value) <= new Date(searchEndTime.value)){
    currentPage.value = 1
    getData()
  }else{
    ElMessage({
      message: '请输入正确的时间范围',
      type: 'warning',
    })
  }
}

// 初始化加载数据
onMounted(() => {
  getTotal()
})

//获取afterchievements月份函数
const getMonth = (arr) => {
  monthArr = []
  if (!arr || arr.length === 0 || !arr[0] || typeof arr[0] !== 'object') {
    return
  }
  for (let i = 0; i < Object.keys(arr[0]).length; i++) {
    monthArr.push(Object.keys(arr[0])[i])
  }
}

// 定义模态框显示状态
const dialogVisible = ref(false)

//获取详情数据
function getDetail(time) {
  let beginTime = ''
  let endTime = ''
  beginTime = searchStartTime.value 
  endTime = searchEndTime.value 

  let data = {
    beginTime,
    endTime,
    pageIndex: currentPage.value,
    pageSize: pageSize.value,
  }
  if (user.roleId == '1' || user.roleId == '2') {
    data.userId = userId.value
  } else if (user.roleId == '5') {
    data.userId = user.userId
  }
  salesCountDetail(data).then((res) => {
    if (res.code == 200) {
      detailData.value = res.dataset.studentList
      total.value = res.dataset.pageCount * pageSize.value
    }
  })
}

// 详情操作
const handleDetail = (row) => {
  dialogVisible.value = true
  if (user.roleId == '1' || user.roleId == '2') {
    userId.value = row.userId
  }
  currentPage.value = 1
  time.value = Object.keys(row).join(', ')
  getDetail(time.value)
}

//取消
function cancel() {
  dialogVisible.value = false
}
// 确认
function confirm() {
  dialogVisible.value = false
}

//当前页码改变
function handleCurrentChange(val) {
  currentPage.value = val
  getDetail(time.value)
}
</script>
  
  <style scoped>
:deep(.className1 .el-input__wrapper){
  border-radius: 12px !important;
}
.search {
  background-color: #0f6ab1;
  color: #fff;
  border: none;
  margin-left: 10px;
  border-radius: 16px;
  padding: 0;
  padding-right: 15px;
  padding-left: 36px;
}

/* 表格区域 */
.class-content {
  width: 90%;
  background-color: #fff;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

/* 表格数据 */
:deep(.el-table thead th) {
  background-color: #fbfcff !important;
}
:deep(.el-table .cell) {
  color: black;
}
:deep(.details1) {
  margin-left: 55px;
}
/* 分页 */
.page {
  margin-top: 50px;
  margin-bottom: 20px;
}
.page1 {
  margin-top: 50px;
  margin-bottom: 20px;
  display: flex;
  justify-content: center;
}
/* 分页背景色 */
:deep(.el-pager .is-active) {
  background-color: #0f6ab1 !important;
}

/* 模态框 */
:deep(.el-overlay .el-overlay-dialog) {
  position: absolute;
}
:deep(.el-overlay) {
  position: absolute;
}
:deep(.el-dialog) {
  padding: 0px;
  width: 800px;
}
:deep(.el-dialog header span) {
  display: inline-block;
  width: 100%;
  background-color: #0f6ab1;
  height: 40px;
  color: white;
  font-size: 15px;
  text-align: center;
  line-height: 40px;
}
:deep(.el-select) {
  width: 200px;
}
:deep(.el-dialog__footer) {
  text-align: center;
  padding-bottom: 20px;
}
:deep(.confirm) {
  margin-left: 50px;
  background-color: #0f6ab1;
}
:deep(.cancel) {
  background-color: #0f6ab1;
  color: white;
}
.tableMaxHeight {
  width: 100%;
  max-height: 280px;
  overflow-y: auto;
}
</style>